package com.LeeCode;

/**
 * 统计值等于子树平均值的节点数
 */

public class Code2265 {
    public static void main(String[] args) {
        Integer[] arr = {4, 8, 5, 0, 1, null, 6};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code2265().averageOfSubtree(root));
    }

    private int count = 0;

    public int averageOfSubtree(TreeNode root) {
        dfs(root);
        return count;
    }

    private int[] dfs(TreeNode root) {
        if (root == null) {
            return new int[]{0, 0};
        }
        int[] left = dfs(root.left), right = dfs(root.right);
        int sum = root.val + left[1] + right[1];
        int total = left[0] + right[0] + 1;
        if (root.val == sum / total) count++;
        return new int[]{total, sum};
    }
}
